// packageFT/release-custom-travel/release-custom-travel.js
const app = getApp()
import { formatDate } from '../../utils/util'
import WxValidate from '../../utils/WxValidate'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    formData: {
      travelCityValue: '',
      chooseTravelCityValue: '',
      travelTimeValue: '',
      travelDays: 0,
      travelTimeStart: '',
      travelTimeEnd: '',
      travelPopulationAdultValue: 0,
      travelPopulationChildrenValue: 0,
      perCapitaBudgetValue: '',
      contactsValue: '',
      phoneValue: '',
      specialRequirementValue: '',
      budgetRadioValue: 0
    },
    chooseTravelCityShow: false,
    travelCityOptions: [],
    travelTimeShow: false,
    travelPopulationColumns: [],
    travelPopulationText: '',
    startDay: null,
    afterTomorrow: null,
    endDay: null
  },

  /**
   * 显示/隐藏弹窗
   * @param {Object} e 
   */
  popupToggle: function(e) {
    const { text, show } = e.currentTarget.dataset
    this.setData({
      [text]: show
    })
  },

  /**
   * 出行城市选择结束
   * @param {Object} e 
   */
  chooseTravelCityFinish: function(e) {
    const { selectedOptions, value } = e.detail;
    const fieldValue = selectedOptions[1].text
    this.setData({
      'formData.travelCityValue': fieldValue,
      'formData.chooseTravelCityValue': value,
      chooseTravelCityShow: false
    })
  },

  /**
   * 出行时间选择确认
   * @param {Object} e 
   */
  travelTimeConfirm: function(e) {
    const start = e.detail[0]
    const end = e.detail[1]
    const startStr = formatDate(start)
    const endStr = formatDate(end)
    const day = (end - start)/1000/60/60/24 + 1
    const travelTimeValue = `${startStr}~${endStr}(${day}天)`
    this.setData({
      'formData.travelDays': day,
      'formData.travelTimeValue': travelTimeValue,
      'formData.travelTimeStart': startStr,
      'formData.travelTimeEnd': endStr,
      travelTimeShow: false
    })
  },

  /**
   * 出行人数选择确认
   * @param {Object} e 
   */
  travelPopulationConfirm: function(e) {
    const { value, index } = e.detail
    if (value[0].population + value[1].population > 30) {
      app.tips('出行人数不能超过30人')
      return
    }
    this.setData({
      'formData.travelPopulationAdultValue': value[0].population,
      'formData.travelPopulationChildrenValue': value[1].population,
      travelPopulationText: `${value[0].text} ${value[1].text}`,
      choosePopulationShow: false,
      'travelPopulationColumns[0].defaultIndex': index[0],
      'travelPopulationColumns[1].defaultIndex': index[1]
    })
  },

  /**
   * 人均预算不限改变
   * @param {Object} e 
   */
  budgetRadioChange: function(e) {
    this.setData({
      'formData.budgetRadioValue': this.data.formData.budgetRadioValue == 1 ? 0 : 1,
      'formData.perCapitaBudgetValue': ''
    })
  },

  /**
   * 人均预算只能输入数字
   * @param {Object} e 
   */
  perCapitaBudgetInput: function(e) {
    let value = e.detail
    value = value.replace(/\D/g, '')
    this.setData({
      'formData.perCapitaBudgetValue': value
    })
  },

  /**
   * 数据双向绑定
   * @param {Object} e 
   */
  updateFormData: function(e) {
    const { formdatakey } = e.currentTarget.dataset
    const value = e.detail
    const key = 'formData.' + [formdatakey]
    this.setData({
      [key]: value 
    })
  },

  /**
   * 取消需求发布
   */
  goBack: function() {
    wx.navigateBack({delta: -1})
  },

  /**
   * 发布需求
   */
  submitForm: function() {
    if (!this.WxValidate.checkForm(this.data.formData)) {
      const error = this.WxValidate.errorList[0]
      app.tips(error.msg)
      return
    }
    console.log(this.data.formData)
    app.tips('发布需求，待完善...')
  },

  /**
   * 获取省市列表(出行城市)
   */
  getAddress: function() {
    wx.showLoading({
      title: '加载中...',
    })
    const _this = this
    let urlStr = app.getNetAddresss("member.member-address.address");
    app._postNetWork({
      url: urlStr,
      success: function(res) {
        const resData = res.data
        if (resData.result == 1) {
          const province = resData.data.province.map(item => {
            const child = resData.data.city.filter(item1 => item1.parentid == item.id).map(item1 => {
              return {
                text: item1.areaname,
                value: item1.id + ''
              }
            })
            return {
              text: item.areaname,
              value: item.id + '',
              children: child
            }
          })
          _this.setData({ travelCityOptions: province})
        } else {
          app.tips(resData.msg)
        }
      },
      complete: function() {
        wx.hideLoading()
      }
    })
  },

  /**
   * 表单验证
   */
  initValidate: function() {
    const rules = {
      travelCityValue: {
        required: true
      },
      travelTimeValue: {
        required: true
      },
      travelPopulationAdultValue: {
        min: 1
      },
      perCapitaBudgetValue: {
        budgetValidate: true,
        min: 1
      },
      contactsValue: {
        required: true
      },
      phoneValue: {
        required: true,
        tel: true
      }
    }
    const message = {
      travelCityValue: {
        required: '请选择出行城市'
      },
      travelTimeValue: {
        required: '请选择出行时间'
      },
      travelPopulationAdultValue: {
        min: '请选择出行人数'
      },
      perCapitaBudgetValue: {
        budgetValidate: '请输入/选择人均预算',
        min: '人均预算必须大于0'
      },
      contactsValue: {
        required: '请输入联系人'
      },
      phoneValue: {
        required: '请输入手机号',
        tel: '请输入正确的手机号码'
      }
    }
    this.WxValidate = new WxValidate(rules, message)
    // 验证人均预算
    const _this = this
    this.WxValidate.addMethod('budgetValidate', () => {
      return _this.data.formData.perCapitaBudgetValue != '' || _this.data.formData.budgetRadioValue != 0
    })
  },

  /**
   * 初始化数据
   * 出行时间设置时间范围/默认开始结束日期
   * 出行人数数据
   */
  initData: function() {
    // 出行时间数据
    const today = new Date()
    // 明天，可选择的开始时间&默认的开始时间
    const tomorrow = new Date(today.getTime() + 24 * 60 * 60 * 1000).toLocaleDateString()
    // 后天，默认结束时间
    const afterTomorrow = new Date(today.getTime() + 24 * 60 * 60 * 1000 * 2).toLocaleDateString()
    // 半年后(181天后)，可选择的最晚时间
    const halfYear = new Date(today.getTime() + 24 * 60 * 60 * 1000 * 181).toLocaleDateString()
    this.setData({
      startDay: tomorrow,
      afterTomorrow,
      endDay: halfYear
    })

    // 出行人数数据
    let adult = []
    let children = []
    for (let i = 0; i < 31; i++) {
      if (i>0) {
        adult.push({
          text: `成人*${i}`,
          population: i
        })
      }
      children.push({
        text: `儿童*${i}`,
        population: i
      })
    }
    this.setData({
      travelPopulationColumns: [
        { values: adult},
        { values: children}
      ]
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.initData()
    this.getAddress()
    this.initValidate()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})